package com.c2rusthub.service.service;

import com.c2rusthub.service.mapper.TaskClaimedMapper;
import com.c2rusthub.service.mapper.TaskMapper;
import com.c2rusthub.service.model.Task;
import com.c2rusthub.service.model.TaskClaimed;
import com.c2rusthub.service.model.TranslatedTask;
import com.c2rusthub.service.request.ClaimTaskRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TaskClaimedService {

    @Autowired
    private TaskClaimedMapper taskClaimedMapper;
    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TaskService taskService;

    @Autowired
    private TranslatedService translatedService;
    // 根据 taskId 获取已领转译任务列表
    public List<TaskClaimed> getClaimedTasksByTaskId(int taskId) {
        return taskClaimedMapper.findClaimedTasksByTaskId(taskId);
    }

    // 设置任务的状态为已完成
    public boolean markTaskAsCompleted(int taskClaimedId) {
        TaskClaimed taskClaimed = taskClaimedMapper.findClaimedTasksById(taskClaimedId);
        Task taskById = taskService.getTaskById(taskClaimed.getTaskId());
        // 调用 Mapper 层的更新方法
        int updatedRows = taskClaimedMapper.updateTaskProgressToCompleted(taskClaimedId);
        TranslatedTask translatedTask = new TranslatedTask();
        translatedTask.setRustUrl(taskClaimed.getRustUrl());
        translatedTask.setClaimUserId(taskClaimed.getClaimUserId());
        translatedTask.setTaskId(taskClaimed.getTaskId());
        translatedTask.setReadmeDetail(taskClaimed.getReadmeDetail());
        translatedTask.setcUrl(taskById.getcUrl());
        translatedService.insertTranslatedTask(translatedTask);
        return updatedRows > 0;  // 如果更新成功，则返回 true
    }

    /**
     * 插入已领转译任务记录
     *
     * @param request 请求体
     */
    public void claimTask(ClaimTaskRequest request) {
        TaskClaimed taskClaimed = new TaskClaimed();
        taskClaimed.setTaskId(request.getTaskId());
        taskClaimed.setClaimUserId(request.getClaimUserId());
        taskClaimed.setRustUrl(request.getRustUrl());
        taskClaimed.setReadmeDetail(request.getReadmeDetail());
        taskClaimed.setProgress("2"); // 默认未完成状态
        taskClaimedMapper.insertTaskClaimed(taskClaimed);
        taskMapper.updateTaskStatus(request.getTaskId());
    }

    /**
     * 更新已认领任务
     *
     * @param request 请求体
     */
    public void updateClaimedTask(ClaimTaskRequest request) {
        // 获取需要更新的任务信息
        TaskClaimed taskClaimed = new TaskClaimed();
//        taskClaimed.setId(request.getTaskClaimedId());
        taskClaimed.setRustUrl(request.getRustUrl());
        taskClaimed.setReadmeDetail(request.getReadmeDetail());

        // 执行数据库更新操作
        taskClaimedMapper.updateTaskClaimed(taskClaimed);
    }
}
